package com.hudson.admin.interceptor;

import com.hudson.admin.util.JwtUtils;
import io.jsonwebtoken.JwtException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String header = request.getHeader("Authorization");
        if (header == null || !header.startsWith("Bearer ")) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "缺少有效的Token");
            return false;
        }

        String token = header.substring(7); // 去掉 "Bearer " 前缀
        if (!validateToken(token)) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "无效的Token");
            return false;
        }
        String userName = jwtUtils.parseToken(token);
        // 设置用户上下文
        UserContext.setUserName(userName);
        return true;
    }

    private boolean validateToken(String token) {
        try {
            jwtUtils.parseToken(token);
            return true;
        } catch (JwtException e) {
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContext.clear(); // 清理线程变量
    }
}
